#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import logging
import json
import re, hashlib,time
# import aiohttp_jinja2
from datetime import datetime
from aiohttp import web
from aioweb import corelib

import db, main


routes = web.RouteTableDef()
module_name = 'users'


@routes.get('/')
@corelib.template('index.html')
async def index(request):
    return {}

@routes.get('/%s' % module_name)
@corelib.template('user.html')
async def user_index(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        path = params.get('path', '/root')
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
    return data

@routes.get('/%s/items' % module_name)
async def user_items(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        index = int(params.get('index', '1'))
        pagesize = int(params.get('pagesize', '36'))
        session = db.create_session()
        page = await main.load_page('User', index, pagesize=pagesize)
        data = dict(data, **page)
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        data['items'] = []
        data['page'] = {'page': {'total': 0, 'pages': 1, 'index': 1, 'size': pagesize}}
    return web.json_response({'code': 0, 'msg': data})

@routes.get('/%s/logininfo' % module_name)
async def user_loginIfo(request):
    data = {}
    try:
        user = request.__user__
        if user:
            session = db.create_session()
            items = session.query(db.LoginInfo).filter_by(user_id=user.id).order_by(db.LoginInfo.id.desc())
            items = [item.single_to_dict() for item in items]
        data['now'] = items[0]
        data['last'] = items[1]
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
    return web.json_response({'code': 0, 'msg': data})

@routes.get('/login')
@corelib.template('login.html')
async def login(request):
    data = {}
    return data


@routes.post('/login')
async def do_login(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        name = params['name']
        password = params['password']
        session = db.create_session()
        user = session.query(db.User).filter(db.User.name == name).first()
        if not user:
            return web.json_response({'code': -1, 'field': 'name', 'msg': '请输入正确的帐号'})
        if user.password != hashlib.sha1(('%s:%s' % (user.name, password)).encode('utf-8')).hexdigest():
            return web.json_response({'code': -1, 'field': 'password', 'msg': '请输入正确的密码'})
        user.login_count += 1
        loginInfo = db.LoginInfo(user_id=user.id, ip=request.remote)
        session.add(loginInfo)
        session.commit()
        rep = web.json_response({'code': 0, 'msg': '登陆成功'})
        main.setCookie(user, rep)
        return rep
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        return web.json_response({'code': -1, 'msg': str(e)})


@routes.get('/register')
@corelib.template('register.html')
async def register(request):
    data = {}
    return data

_RE_EMAIL = re.compile(
    r'^[a-z0-9\.\-\_]+\@[a-z0-9\-\_]+(\.[a-z0-9\-\_]+){1,4}$')
_RE_SHA1 = re.compile(r'^[0-9a-f]{40}$')


@routes.post('/register')
async def do_register(request):
    params = await corelib.parse_param(request)
    name = params['name']
    email = params['email']
    password = params['password']
    if not name or not name.strip():
        return web.json_response({'code': -1, 'field': 'name', 'msg': 'name is null'})
    if not email or not _RE_EMAIL.match(email):
        return web.json_response({'code': -1, 'field': 'email', 'msg': 'email 格式不正确'})
    if not password or not _RE_SHA1.match(password):
        return web.json_response({'code': -1, 'field': 'password', 'msg': '密码格式不正确'})
    session = db.create_session()
    user = session.query(db.User).filter_by(email=email).first()
    if user:
        return web.json_response({'code': -1, 'field': 'email', 'msg': '邮箱已注册'})
    user = db.User(name=name, password=password, email=email, admin=False)
    session.add(user)
    session.commit()
    data = web.json_response({'code': 0, 'msg': '注册成功'})
    return data


@routes.get('/logout')
@corelib.template('index.html')
async def logout(request):
    data = {}
    try:
        user = request.__user__
        if user:
            session = db.create_session()
            loginInfo = session.query(db.LoginInfo).filter_by(user_id=user.id).order_by(db.LoginInfo.id.desc()).first()
            if loginInfo: loginInfo.logout_at = datetime.now()
            session.commit()
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
    rep = web.HTTPFound(location='/')
    main.setCookie(None, rep)
    raise rep
    return data
